import { SET_TOKEN, SET_USER_INFO, SET_USER_MENU, SET_USER_ROLE } from '../actions/types'
import { decodeMsg, encodeMsg } from '../../utils'

let cache = sessionStorage.getItem('common-state')
if(!!cache) {
    cache = JSON.parse(decodeMsg(cache))   //进行 加密
}else{
    cache = {}
}

//设置初始值
const initState ={
    token: cache.token || '',
    userInfo: cache.userInfo || {},
    userMenu: cache.userMenu || [],
    userRole: cache.userRole || []
}
 


const commonReducer = (state = initState ,action) => {
    let newState
    switch(action.type) {
        case SET_TOKEN:
             newState = {
                ...state,
                token:action.token  //这里存入数据,
            }
            sessionStorage.setItem('common-state',encodeMsg(JSON.stringify(newState))) //加密存入sessionStorage
            return newState
        case SET_USER_INFO:
            newState = {
                ...state,
                userInfo:action.userInfo
            }
            sessionStorage.setItem('common-state',encodeMsg(JSON.stringify(newState)))
            return newState
        case SET_USER_MENU:
            newState = {
                ...state,
                userMenu:action.userMenu
            }
            sessionStorage.setItem('common-state',encodeMsg(JSON.stringify(newState)))
            return newState
        case SET_USER_ROLE:
            newState = {
                ...state,
                userRole:action.userRole
            }
            sessionStorage.setItem('common-state',encodeMsg(JSON.stringify(newState)))
            return newState
        default:
            return JSON.parse(JSON.stringify(initState)) //深拷贝 不能
    }
}
export default commonReducer